package com.example.demo.Component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketComponent {
    public ConcurrentHashMap<Integer, WebSocketSession> map= new ConcurrentHashMap<>();
    //用户上线
    public  void online(int userid, WebSocketSession session ){
        //多开的限制策略
        if(map.get(userid)!=null){
            System.out.println("该用户已经登录");
            return;
        }
        map.put(userid,session);
        System.out.println(userid+"上线");

    }
    //用户下线
    public void  offline(int userid,WebSocketSession session){
        WebSocketSession exitSession=map.get(userid);
        if(exitSession==session){
            map.remove(userid);
        }
        System.out.println(userid+"下线");
    }
    //根据userid获取到session
    public  WebSocketSession getSession(int userid){
        WebSocketSession session =map.get(userid);
       return session;
    }
}
